package edu.umassd.visual.options;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import edu.umassd.raddacl.util.FilesUtil;
import edu.umassd.raddacl.util.Locations;
import edu.umassd.visual.AttributeNames;
import edu.umassd.visual.DataPoints;
import edu.umassd.visual.View;
import edu.umassd.visual.util.ClusterFileSystemLoader;

@Component
public class Load implements ActionListener
{
	@Value("${dataset.output.dir}")
	private Path path;

	@Autowired
	private View view;

	@Autowired
	private DataPoints data;

	@Autowired
	private ClusterFileSystemLoader loader;

	@Autowired
	private List<JComboBox<String>> axis;

	@Autowired
	private AttributeNames names;

	@Autowired
	private Locations locations;

	@Override
	public void actionPerformed(ActionEvent e)
	{
		JFileChooser chooser = new JFileChooser(path.toFile());
		chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

		int selection = chooser.showOpenDialog(null);

		if (selection == JFileChooser.APPROVE_OPTION)
		{
			Path clusterFile = chooser.getSelectedFile().toPath();

			locations.changeDataSet(FilesUtil.getName(clusterFile));

			loader.setLocation(clusterFile);
			loader.loadClusters();

			try
			{
				names.loadNames(locations.getTitleFile());
			}
			catch (IOException e1)
			{
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			for (int i = 0; i < axis.size(); i++)
			{
				JComboBox<String> box = axis.get(i);

				DefaultComboBoxModel<String> model = (DefaultComboBoxModel<String>) box
						.getModel();

				model.removeAllElements();

				for (String s : names)
				{
					model.addElement(s);
				}

				box.setSelectedIndex(i);
			}

			data.setXIndex(0);
			data.setYIndex(1);
			view.setDataSetBounds(data.getBounds());
		}
	}
}
